package com.wehealth;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.wehealth.dm.User;
import com.wehealth.util.DataManger;
import com.wehealth.util.GetUrl;
import com.wehealth.util.VerifyCode;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Register extends Fragment{
	
	private MainActivity mConext;
	private EditText accountET;
	private EditText phoneNumET;
	private EditText pswET;
	private EditText trim_pswET;
	private EditText sms_codeEt;
	private ImageView  manImg;
	private ImageView  womenImg;
	private int sexValue = 0;
	private User user;
	private DataManger  mDataManger;
	private static  String JSONResult;
	private ProgressBar mProgress;
	private AlertDialog dialog;
	
	private static final int NET_ERROR = -100;
	private static final int REGIST_ERROR=-101;
	private static final int REGIST_PHONENUM_ERROR= -102;
	private static final int REGIST_SERVICE_TREM_ERROR = -103;
	private static final int REGIST_VERIFY_CODE_ERROR = -104;
	private static final int REGIST_PASSWORD_ERROR = -105;
	private boolean service_trim_state = true;
	private static final int REGIST_SUBMIT = 0;
	private static final int REGIST_VERIFY =1;
	private int connetMode = 0;
	private String phoneNum; 
	private String mVerifyCode;
	private VerifyCode mverify;
	private Button regist_verify;
	private int timerVaule = 0;
	private Timer timer;
	private VerifyCodeListener mVerifyListener;
	private TimerTask task;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return  inflater.inflate(R.layout.reigister, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		mConext =(MainActivity)getActivity();
		mProgress =(ProgressBar)mConext.findViewById(R.id.regist_progress);
		mDataManger = mConext.getDataManger();
		mverify = VerifyCode.getInstance();
		TextView title=(TextView)mConext.findViewById(R.id.header_title);
		String titlename = mConext.getString(R.string.register_title);
		title.setText(titlename);
		int color =mConext.getResources().getColor(R.color.text_color_green);
		title.setTextColor(color);
		
		//CheckBox service_term =(CheckBox)mConext.findViewById(R.id.register_service_term);
		TextView service_term_tx =(TextView)mConext.findViewById(R.id.register_caluse);
		Spannable sText = new SpannableString(service_term_tx.getText());
		sText.setSpan(new ForegroundColorSpan(Color.RED), 3, 8, 0 );
		service_term_tx.setText(sText);
		final ImageView service_term =(ImageView)mConext.findViewById(R.id.register_service_term);
		service_term.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                 if(service_trim_state){
                     service_trim_state =false;
                     service_term.setImageResource(R.drawable.btn_check_off);
                 }else{
                     service_trim_state =true;
                     service_term.setImageResource(R.drawable.btn_check_on);
                 }
            }
        });
		
		Button bBack = (Button) mConext.findViewById(R.id.header_bBack);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{		
				    mConext.switchContentHome();
				}
			});
		 
		 accountET =(EditText)mConext.findViewById(R.id.register_user_name_et);
		 phoneNumET =(EditText)mConext.findViewById(R.id.regist_tele_number_et);
		 pswET =(EditText)mConext.findViewById(R.id.regist_psw_et);
		 trim_pswET =(EditText)mConext.findViewById(R.id.regist_trim_psw_et);
		 sms_codeEt =(EditText)mConext.findViewById(R.id.rgister_indentfy_sms_et);
		 
		 
	
		 
		 manImg =(ImageView)mConext.findViewById(R.id.regist_man_img);
		 womenImg =(ImageView)mConext.findViewById(R.id.regist_women_img);
		 manImg.setVisibility(View.VISIBLE);
		 womenImg.setVisibility(View.INVISIBLE);
		 
		 TextView man = (TextView)mConext.findViewById(R.id.regist_man_tx);
		 man.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				if(sexValue!=0){
					sexValue =0;
					 manImg.setVisibility(View.VISIBLE);
					 womenImg.setVisibility(View.INVISIBLE);
				}
			}
		});
		 
		 TextView women = (TextView)mConext.findViewById(R.id.regist_women_tx);
		 women.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(sexValue!=1){
					sexValue =1;
					 manImg.setVisibility(View.INVISIBLE);
					 womenImg.setVisibility(View.VISIBLE);
				}
			}
		});

		 Button  submit =(Button)mConext.findViewById(R.id.register_submit_bt);
		 submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				user = mConext.getUserInfo();
				String psw = pswET.getText().toString().trim();
				String trim_psw = trim_pswET.getText().toString().trim();
				String account = accountET.getText().toString().trim();
				String sms_code=sms_codeEt.getText().toString().trim();

				int psw_count = psw.length();
				boolean accountRight = account.matches("[0-9A-Za-z]*");
				boolean pswRight = psw.matches("[0-9A-Za-z]*");
				
//				Log.d("SIMMON"," accountRight= "+accountRight);
//				Log.d("SIMMON"," psw_count= "+psw_count);
//				Log.d("SIMMON"," pswRight= "+pswRight);
//				Log.d("SIMMON"," sms_code= "+sms_code);
//				Log.d("SIMMON"," sms_code= "+sms_code);
				

				if(psw==null ||psw_count<6||!pswRight|| !(psw.equals(trim_psw))||
				        !accountRight ||!service_trim_state){
				      openRegistDialog(REGIST_ERROR);
				      return;
				}
				if(!sms_code.equals(mVerifyCode)){
				    openRegistDialog(REGIST_VERIFY_CODE_ERROR);
				    return;
				}
				
				if(!psw.equals(trim_psw)){
				    openRegistDialog(REGIST_PASSWORD_ERROR);
				    return;
				}
				    
				if(!service_trim_state){
				    openRegistDialog(REGIST_SERVICE_TREM_ERROR);
				    return;
				}

					user.setAccount(account);
					Log.d("SIMMON","phoneNum=   "+phoneNum);
					user.setPhoneNumber(phoneNum);
					user.setPassword(psw);
					user.setUserSex(sexValue);
					connetMode = REGIST_SUBMIT;
					mProgress.setVisibility(View.VISIBLE);
					RegistToConnServer();
			}
		});
		 
		 mVerifyListener =new VerifyCodeListener();
		 regist_verify =(Button)mConext.findViewById(R.id.regist_indentfy_sms_bt);
		 regist_verify.setOnClickListener(mVerifyListener);
	}

	private void openRegistDialog(final int result){
		String psw = pswET.getText().toString().trim();
		String trim_psw = trim_pswET.getText().toString().trim();
	   String login_result = mConext.getString(R.string.regist_fail);
//	     Log.d("SIMMON","######result  ="+result);
       switch (result) {
       case -3:
           login_result = getString(R.string.regist_phone_num_fail);
           break;
       case -2:
           login_result = getString(R.string.regist_fail3);
           break;
       case -1:
           login_result = getString(R.string.regist_fail);
           break;
       case 0:
           login_result = getString(R.string.regist_fail2);
           break;
       case NET_ERROR:
           login_result = getString(R.string.net_connet_fail);
           break;
       case REGIST_PHONENUM_ERROR:
           login_result = getString(R.string.regist_phone_num_error);
           break;
       case REGIST_SERVICE_TREM_ERROR:
           login_result = getString(R.string.regist_service_error);
           break;
       case REGIST_VERIFY_CODE_ERROR:
           login_result = getString(R.string.regist_verify_code_error);
           break;
       case REGIST_PASSWORD_ERROR:
           login_result = getString(R.string.regist_service_error);
           break;
       default:
           if(result > 0){
               login_result = getString(R.string.regist_success);
               mDataManger.delUserDate();
               mDataManger.setUserID(result);
               user.setUserId(result);
               mDataManger.storeUserInfo(user);
           }else{
               login_result =getString(R.string.regist_fail);
           }
           break;
   }
	  
	    
	    
        final AlertDialog.Builder builder = new AlertDialog.Builder(mConext); 
        View view = LayoutInflater.from(mConext).inflate(R.layout.dialog_self_viewbt,null);
        TextView textview = (TextView)view.findViewById(R.id.dialog_self_tx);
        textview.setText(login_result);
        Button okBt =(Button)view.findViewById(R.id.dialog_self_bt);
        String okBtBtStr ="确定";
        okBt.setText(okBtBtStr);
        okBt.setOnClickListener(new OnClickListener() {
           
           @Override
           public void onClick(View arg0) {
               // TODO Auto-generated method stub
               if(result > 0){
                   Questionnaire_page1 vHome = new Questionnaire_page1();
                      //mConext.switchContent(vHome);    
                   mConext.switchContentNoStack(vHome);    
                   }
               dialog.cancel();
           }
       });
        builder.setView(view);
        dialog=builder.create();
        dialog.show();
	    
	    
		
	}
	
	
	private void RegistToConnServer(){
        new Thread(){
            @Override
            public void run(){
                try {
                    if(connetMode == REGIST_SUBMIT){
                        initDataFromNet();
                    }else if(connetMode == REGIST_VERIFY){
                            //Log.d("SIMMON"," RegistToConnServer  REGIST_VERIFY");
                            initDataFromNetVerifyCode();
                          }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Message message = new Message();
                message.what = 0;
            handler.sendMessage(message);
            }
            }.start();
}


private void initDataFromNet() throws IOException{
     String urlAPI = GetUrl.Register_Url();
     HttpPost httpRequest= new HttpPost(urlAPI);
     //loginName=stormer101010&password=123123&amp;sex=男&amp;phone=15230188888

     List <NameValuePair> params = new ArrayList <NameValuePair>();
     params.add(new BasicNameValuePair("loginname",user.getAccount()));
     params.add(new BasicNameValuePair("password",user.getPassword()));
     String sex;
     if(user.getUserSex()==0){
       sex = getString(R.string.register_user_sex_man);
      }else{
       sex = getString(R.string.register_user_sex_women);
      }
     Log.d("SIMMON","phoneNum="+phoneNum);
     params.add(new BasicNameValuePair("sex",sex));
     params.add(new BasicNameValuePair("phone",user.getPhoneNumber()));
     
     try{
         httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
         HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
         if(httpResponse.getStatusLine().getStatusCode() == 200)
         {
             JSONResult = EntityUtils.toString(httpResponse.getEntity());
             //Log.d("SIMMON:", "JSONResult="+JSONResult);
         }
     } catch(Exception e){
         Log.e("SIMMON:",  e.toString());
     }

}

private Handler handler =new Handler(){
    @Override
    public void handleMessage(Message msg){
        super.handleMessage(msg);
        mProgress.setVisibility(View.GONE);
       switch (msg.what) {
            case 0:
                if(JSONResult!=null){
                    BindNewsData(JSONResult);
                    JSONResult =null;
                }else{
                    mProgress.setVisibility(View.GONE);
                    openRegistDialog(NET_ERROR);
                    }
              break;
            case 1:
              setVerifyButtonValue();
              break;
            default:
                break;
        }
   
    }
};

private void BindNewsData(String strJSON){
    try{
            JSONObject jsonObject = new JSONObject(strJSON);
            String result_str = jsonObject.getString("result");
            Log.d("SIMMON"," result_str="+result_str);
            int result = Integer.valueOf(result_str);
            Log.d("SIMMON"," result="+result);
            if(connetMode ==REGIST_SUBMIT){
            openRegistDialog(result);
            }else{
               if(result == 1){
                 timerVaule = 60;
                 starTimer();
                 }
               }
            
    }catch(JSONException ex)
    {
            Log.e("JSON Error: ", ex.toString()); 
    }
    
}

private void initDataFromNetVerifyCode() throws IOException{
    String urlAPI = GetUrl.GetVerifyCode_Url();
    HttpPost httpRequest= new HttpPost(urlAPI);
    List <NameValuePair> params = new ArrayList <NameValuePair>();
    params.add(new BasicNameValuePair("phone",phoneNum));
    
    String messga="【卫健康】您的注册验证码为:"+mVerifyCode;
    Log.d("SIMMON","messga = "+messga);
    params.add(new BasicNameValuePair("message",messga));
    String KEY ="MIICdgIBADANBgkqhkiG9w0BAQEFAA";
    params.add(new BasicNameValuePair("key",KEY));
    try{
        httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
        if(httpResponse.getStatusLine().getStatusCode() == 200)
        {
            JSONResult = EntityUtils.toString(httpResponse.getEntity());
        }
    } catch(Exception e){
        Log.e("SIMMON:",  e.toString());
    }

}


private void setVerifyButtonValue(){
    String tx;
    if(timerVaule>0){
     String index = String.valueOf(timerVaule);
     tx = "等待"+index + "秒";
     timerVaule--;
    }else{
        tx = getString(R.string.register_indentfy_sms); 
        regist_verify.setOnClickListener(mVerifyListener);
        timer.cancel();
        timer = null;
        task.cancel();
        task=null;
        
    }
    regist_verify.setText(tx);   
 }
	
private void starTimer(){
    regist_verify.setOnClickListener(null);
    if(timer==null){
    timer = new Timer(true);
    }
    
    if(task==null){
    	 task = new TimerTask() {
    	    
    	    @Override
    	    public void run() {
    	        // TODO Auto-generated method stub
    	        Message msg = new Message();
    	        msg.what = 1;
    	        handler.sendMessage(msg);
    	    }
    	};
    }
    
    if(timer!=null && task!=null){
    	timer.schedule(task,1000, 1000); //延时1000ms后执行，1000ms执行一次
    }
}
	



class VerifyCodeListener implements View.OnClickListener{

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        phoneNum = phoneNumET.getText().toString().trim();
        boolean isPhoneNumRight = phoneNum.length() < 11?false:true;
        if(!isPhoneNumRight){
            openRegistDialog(REGIST_PHONENUM_ERROR);
            }else{
             mVerifyCode = mverify.createCode();
             connetMode =REGIST_VERIFY;
             mProgress.setVisibility(View.VISIBLE);
             RegistToConnServer();
            }
    }
    
}

}
